package cc.rengu.redp.bizimpl.upmp.service.impl;


import cc.rengu.igas.bomp.facade.BompMchntQueryService;
import cc.rengu.igas.bomp.facade.request.MchntInfoListQueryRequest;
import cc.rengu.igas.momp.facade.bean.McMchntInfoBean;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.TBNotifyInfoMapper;

import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.TBNotifyInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.domain.RedpResponse;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author System
 * @since 2022-04-16
 */

@Slf4j
@Service
//@DS("upmp")
public class TBNotifyInfoServiceImpl extends ServiceImpl<TBNotifyInfoMapper, TBNotifyInfo> implements TBNotifyInfoService {
    @Autowired
    private NtcAdvMchntAreaOrgservice ntcAdvMchntAreaOrgService;
    @Autowired
    private IUpmpBMchntBaseInfoService iUpmpBMchntBaseInfoService;
    @Autowired
    private IUpmpBTradeAreaInfoService iUpmpBTradeAreaInfoService;
    @Autowired
    private IUpmpPrivilegeCheckService iUpmpPrivilegeCheckService;
    @Autowired
    private CommissionMarketService commissionMarketService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpSysSeqService updateParamValue;

    @DubboReference(version = "${dubbo.protocol.version}", check = false)
    private BompMchntQueryService bompMchntQueryService;

    @Override
    public RedpResponse uploadntc(MultipartFile excelFile) throws IOException, RedpException {
        if (excelFile == null) {
            log.error("请选择文件");
            return RedpResponse.getInstance().failure().message("请选择文件");
        }
        String originalFilename = excelFile.getOriginalFilename();
        if (!originalFilename.endsWith(".xls") && !originalFilename.endsWith(".xlsx")) {
            log.error("文件不是excel类型");
            return RedpResponse.getInstance().failure().message("文件不是excel类型");
        }
        // 可成功添加的列表
        List<McMchntInfoBean> mchntInfoList = new ArrayList<>();
        // 存在错误的列表
        List<McMchntInfoBean> errorList = new ArrayList<>();

        //String selectedOrgInfoList = request.getParameter("selectedOrgInfoList");

        //
        Workbook workbook = null;
        if (originalFilename.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook(excelFile.getInputStream());
        } else if (originalFilename.endsWith(".xls")) {
            workbook = new HSSFWorkbook(excelFile.getInputStream());
        } else {
            log.info("类名-方法名","NotifyInfoController-"+"getDataFromExcelNtc");
        }
        Sheet sheetAt = workbook.getSheetAt(0);
        int lastRowNum = sheetAt.getLastRowNum();
        if (lastRowNum > 500) {
            return RedpResponse.getInstance().failure().message("上传数据不能超过500行");
        }
        if (lastRowNum < 1) {
            return RedpResponse.getInstance().failure().message("请填入上传的商户号");
        }
        List<String> mcNos = new ArrayList<>();
        for (int i = 1; i <= lastRowNum; i++) {
            Row rowTitle = sheetAt.getRow(i);
            if (rowTitle != null) {// 行不为空
                // 读取cell
                Cell cell = rowTitle.getCell(0);
                if (cell != null) {
                    if (cell.getCellType() != Cell.CELL_TYPE_STRING) {
                        return RedpResponse.getInstance().failure().message("请将上传文件数据的格式设置为文本格式");
                    }

                    String mchntNo = CommonUtils.getValue(cell);
                    mcNos.add(mchntNo);
                }
            }
        }
        // 去重
        mcNos = mcNos.stream().distinct().collect(Collectors.toList());
        //
        MchntInfoListQueryRequest param = new MchntInfoListQueryRequest();
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        mcNos.forEach((e) -> {
            param.setMchntNo(e);
            Map<String, Object> maps = null;
            maps = commissionMarketService.queryMcNoList(user, param, genMerOrder(user));
            if (null != maps.get("results")) {
                List resultList = (List) maps.get("results");
                Map mcMap = (Map) resultList.get(0);
                McMchntInfoBean mchntInfo = new McMchntInfoBean();
                mchntInfo.setMchntNo((String) mcMap.get("id"));
                mchntInfo.setMchntName((String) mcMap.get("name"));
                mchntInfo.setMchntType("0");//----0-商户 1-商圈

                Boolean isFeeMchntFlag = commissionMarketService.checkFeeMchnt(user, e,bompMchntQueryService, genMerOrder(user));
                // 可成功添加
                mchntInfoList.add(mchntInfo);
            } else {
                McMchntInfoBean mchntInfo1 = new McMchntInfoBean();
                mchntInfo1.setMchntNo(e);
                mchntInfo1.setMchntType("0");//----0-商户 1-商圈
                errorList.add(mchntInfo1);
            }
        });
        Map<String, List<McMchntInfoBean>> resultMap = new HashMap<>();
        resultMap.put("successData", mchntInfoList);
        resultMap.put("errorData", errorList);
        return RedpResponse.getInstance().success().message("导入文件成功").data(resultMap);
    }

    @Override
    public IPage<TBNotifyInfo> findByPage(QueryRequest request, TBNotifyInfo info) {
        try {
            LambdaQueryWrapper<TBNotifyInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(info.getInstId())) {
                queryWrapper.likeRight(TBNotifyInfo::getInstId, info.getInstId());
            }
            if (StringUtils.isNotBlank(info.getTitle())) {
                queryWrapper.like(TBNotifyInfo::getTitle, info.getTitle());
            }
            queryWrapper.orderByDesc(TBNotifyInfo::getCreateTime);

            Page<TBNotifyInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, true);
            return this.page(page,queryWrapper);
        } catch (Exception e) {
            log.error("查询失败", e);
            return null;
        }
    }


    @Override
    public List<TBNotifyInfo> findUserNotify(String userId) {
//        Wrapper.
//        return baseMapper.selectObjs(new TBNotifyInfo().setInstId(userId));
        return null;
    }
    @Override
    public List<TBNotifyInfo> findByName(String instId, String roleName) {
        QueryWrapper queryWrapper=new QueryWrapper<>();
        if (instId!=null){
        queryWrapper.like("INST_ID",instId);
        }if (roleName!=null){
            queryWrapper.like("TITLE",roleName);
        }
        return baseMapper.selectObjs(queryWrapper);
    }

    @Override
    public TBNotifyInfo findById(String id) {
        return baseMapper.selectById(id);
    }

    @Override
    public OperationResult createNotify(TBNotifyInfo entity) {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
//        User user=AuthContextHolder
                    UpmpPrivilegeCheck privilegeCheck = iUpmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "notify:add");
            if (null != privilegeCheck && "Y".equals(privilegeCheck.getChecked())) {
                //需要审核
//                entity.setOprId(user.getUsername());
                entity.setNotifyStatus(BizDataStatusEnum.STATUS_DRAFT.getType());
                entity.setAuditStatus(BusinessContainer.check_sta_01);
                save(entity);
            } else {
                //不需要审核
//                entity.setOprId(user.getAuthUid())
                entity.setPublishTime(entity.getCreateTime());
                entity.setNotifyStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                entity.setAuditStatus(BusinessContainer.check_sta_02);
                baseMapper.insert(entity);
            }
        return OperationResult.buildSuccessResult("id",  entity.getId());
    }

    @Override
    public void auditNotify(String notifyid, String notify) {

        TBNotifyInfo tbNotifyInfo = baseMapper.selectById(notifyid);
        if (tbNotifyInfo.getAuditStatus().equals(BusinessContainer.check_sta_01)){
            if (notify.equals(BusinessContainer.check_sta_02)){
                tbNotifyInfo.setAuditStatus(BusinessContainer.check_sta_02);
                tbNotifyInfo.setNotifyStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                baseMapper.updateById(tbNotifyInfo);
            }else{
                tbNotifyInfo.setAuditStatus(BusinessContainer.check_sta_03);
                baseMapper.updateById(tbNotifyInfo);
            }
        }else if(tbNotifyInfo.getAuditStatus().equals(BusinessContainer.check_sta_41)){
            if (notify.equals(BusinessContainer.check_sta_42)){
                tbNotifyInfo.setAuditStatus(BusinessContainer.check_sta_42);
                tbNotifyInfo.setNotifyStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                baseMapper.updateById(tbNotifyInfo);
            }else{
                tbNotifyInfo.setAuditStatus(BusinessContainer.check_sta_43);
                baseMapper.updateById(tbNotifyInfo);
            }
        }
    }

    @Override
    public void deleteNotify(String[] NotifyIds) throws Exception {
        //同步流程引擎
        List<String> list = Arrays.asList(NotifyIds);
        int i = baseMapper.deleteBatchIds(list);
        // 重新将这些用户的角色和权限缓存到 Redis中
//        this.upmpUserManager.loadUserPermissionRoleRedisCache(userIds);
    }

    @Override
    public void updateNotify(TBNotifyInfo entity) throws Exception {
        UpmpPrivilegeCheck privilegeCheck = iUpmpPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(entity.getInstId(), "notify:update");
        if (null != privilegeCheck && "Y".equals(privilegeCheck.getChecked())){
            //需要审核
            entity.setAuditStatus(BusinessContainer.check_sta_41);
        } else {
            //不需要审核
            entity.setPublishTime(entity.getCreateTime());
            entity.setAuditStatus(BusinessContainer.check_sta_42);
        }
       baseMapper.updateById(entity);
        // 重新将这些用户的角色和权限缓存到 Redis中
//        this.upmpUserManager.loadUserPermissionRoleRedisCache(userIds);
    }

    @Override
    public List<TBNotifyInfo> getAllNotify(TBNotifyInfo role) {
        return null;
    }


    @Override
    public OperationResult saveData(TBNotifyInfo notify) {
        return OperationResult.buildSuccessResult("数据保存处理完成", save(notify));

    }

    /**
     * 生成交易流水号（格式：MO + 8位日期 + 8位顺序号）
     */
    private String genMerOrder(UpmpUserInfoVO user) {
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService,user.getInstId());
        // 代理商编码前缀：MO（merOrder简写）
        String prefix = user.getInstId() + "MCMP";
        // 自动生成一级代码
        String paramCode = BusinessContainer.COMM_PARAM_CODE;
        // 生成序列号
        String seqNum = updateParamValue.updateParamValue(paramCode, "MER_ORDER", channelId);
        // 8位日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String date8 = sdf.format(new Date());

        // 交易流水号
        String merOrder = prefix + date8 + String.format("%08d", Integer.parseInt(seqNum));
        return merOrder;
    }
}
